package com.king.base.rest.picture;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.king.base.aop.Log;
import com.king.base.auth.utils.JwtTokenUtil;
import com.king.base.domain.picture.Picture;
import com.king.base.service.picture.PictureService;
import com.king.base.utils.PageUtil;
import com.king.base.utils.RequestHolder;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

/**
 * @author TianYZ
 * @date 2019-06-16
 */
@RestController
@RequestMapping("/api/tools/picture")
@Api(value = "picture",description = "图片管理Controller")
public class PictureController {

    @Autowired
    private PictureService pictureService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Log(description = "查询图片")
    @GetMapping(value = "/page")
    public ResponseEntity page(Picture resources, Pageable pageable){
        IPage<Picture> pictureIPage = pictureService.page(new Page<>(pageable.getPageNumber(), pageable.getPageSize()), Wrappers.<Picture>lambdaQuery()
                .like(StringUtils.isNotBlank(resources.getFileName()), Picture::getFileName, resources.getFileName())
                .orderByDesc(Picture::getId));
        return new ResponseEntity(PageUtil.toPage(pictureIPage),HttpStatus.OK);
    }

    /**
     * 上传图片
     * @param file
     * @return
     * @throws Exception
     */
    @Log(description = "上传图片")
    @PostMapping(value = "/upload")
    public ResponseEntity upload(@RequestParam MultipartFile file){
        String userName = jwtTokenUtil.getLoginName(RequestHolder.getHttpServletRequest());
        Picture picture = pictureService.upload(file,userName);
        Map map = new HashMap();
        map.put("errno",0);
        map.put("id",picture.getId());
        map.put("data",new String[]{picture.getUrl()});
        return new ResponseEntity(map,HttpStatus.OK);
    }

    /**
     * 删除图片
     * @param id
     * @return
     */
    @Log(description = "删除图片")
    @DeleteMapping(value = "/delete/{id}")
    public ResponseEntity delete(@PathVariable Long id) {
        pictureService.delete(pictureService.findById(id));
        return new ResponseEntity(HttpStatus.OK);
    }
}
